package com.enterprise.domXml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;










import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlConfigure {
	
	private static DocumentBuilderFactory dbf;
	private static Document dom;
	private static DocumentBuilder db;
	private static String pathString;
	public XmlConfigure(String...path){
		pathString=path[0].replace("%20", " ");
		dbf=DocumentBuilderFactory.newInstance();
		try {
			db=dbf.newDocumentBuilder();
		
				dom=db.parse(path[0]);
			
		}  catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(pathString);
		
	}
		
	
	/**
	 * 根据网站配置标签名，获取其对应值
	 * @param label
	 * @return
	 */
	public  String getVale(String label){
		
		
		
		NodeList nodeList=dom.getElementsByTagName(label);
		if(nodeList!=null&&nodeList.getLength()>0){
			
			return nodeList.item(0).getTextContent();
			
			
		}
		return "找不到配置信息";
	}
	public void setVale(String label,String value){
		
		NodeList nodeList=dom.getElementsByTagName(label);
		if(nodeList!=null&&nodeList.getLength()>0){
			nodeList.item(0).setTextContent(value);
		}
		
		//写入硬盘
		try {
			TransformerFactory transformerFactory = TransformerFactory.newInstance();

			Transformer transformer = transformerFactory.newTransformer();
			DOMSource domSource = new DOMSource(dom);
			// 设置编码类型
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			StreamResult result = new StreamResult(new FileOutputStream(pathString));
			transformer.transform(domSource, result);
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		 

		  
	}
	
	
}
